#!/usr/bin/env python
# -*- coding: utf-8 -*-

from google.appengine.api import users
from google.appengine.ext import db
from gaeo.controller import Controller
from application import models

class Forum(Controller):

    def before_action(self):
        action = self.params['action']
        if action in ['new', 'create', 'edit']:
            self.view.user = users.get_current_user()
            self.view.logout_path = users.create_logout_url('/')

    def new(self):
        pass
    
    def create(self):       
        try:
            serial = models.ForumSerial.get_or_insert("taipei_gtug_forum")
            
            p = self.params.get('forum', None)
            if p is None:
                raise Exception('No forum parameters')
            
            f = models.Forum(key_name='forum_%d' % serial.value,
                             parent=serial,
                             title=p['title'],
                             summary=p['desc'],
                             category=db.Category(p['category']),
                             permalink=p['permalink'])
            key = f.put()
            serial.value += 1
            serial.put()
            
            if self.is_xhr:
                self.json_output({
                    'ok': True,
                    'forumKey': str(key)
                })
            else:
                self.redirect('/forum/new')
        except:
            raise
        
    def edit(self):
        """
        Edit forum page.
        """
        f = models.Forum.all()
        self.view.forums = f.order('created')
        
    def update(self):
        """
        Update the forum.
        """
        try:
            f = self.params.get('forum')
            if f is None:
                raise Exception('No forum parameters')
            
            forum = models.Forum.get(f['key'])
            forum.update_attributes(title=f['title'], summary=f['summary'])
            
            self.redirect('/forum/edit')
        except:
            raise
        
    def feed(self):
        #feed_type = self.params.get('type')
        permalink = self.params.get('permalink')
        forum = models.Forum.get_by_permalink(permalink)
        topics = models.Topic.get_topics_by_forum(forum)
        
        if topics:
            updated = topics[0].updated
        else:
            updated = forum.created
        
        self.view.forum = forum
        self.view.data = {
            'topics': topics,
            'updated': updated
        }
        
    def show(self):
        """ Forum entry """
        permalink = self.params.get('permalink')
        forum = models.Forum.get_by_permalink(permalink)
        
        self.view.forum = forum
        self.view.topics = models.Topic.get_topics_by_forum(forum)
        self.view.page_title = u'%s &laquo; Taipei GTUG Forum' % forum.title
        self.view.breadcrumb = u'<a href="/" class="breadcrumb-link">首頁</a> &raquo; 討論區: %s' % forum.title
        if getattr(self.view, 'member', None):
            self.view.can_post = True
        else:
            self.view.can_post = not forum.readonly and getattr(self.view, 'member', None) is not None